export interface ChatMessage {
  role: 'user' | 'assistant'
  content: string
}

export async function* streamMessage(messages: ChatMessage[]): AsyncGenerator<string> {
  try {
    console.log('Sending request with messages:', messages)
    const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Accept': 'text/event-stream',
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${import.meta.env.VITE_DEEPSEEK_API_KEY}`
      },
      body: JSON.stringify({
        model: 'deepseek-chat',
        messages: messages,
        stream: true,
        temperature: 0.7,
        max_tokens: 2000
      })
    })

    if (!response.ok) {
      const errorText = await response.text()
      console.error('API response not ok:', response.status, errorText)
      throw new Error(`API 请求失败: ${response.status} - ${errorText}`)
    }

    if (!response.body) {
      throw new Error('Response body is null')
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder()

    try {
      while (true) {
        const { value, done } = await reader.read()
        if (done) break

        const chunk = decoder.decode(value)

        const lines = chunk
          .split('\n')
          .map(line => line.trim())
          .filter(line => line.startsWith('data: '))

        for (const line of lines) {
          const json = line.slice(6)
          if (json === '[DONE]') {
            console.log('Stream completed')
            return
          }

          try {
            const parsed = JSON.parse(json)
            const content = parsed.choices?.[0]?.delta?.content
            if (content) {
              yield content
            }
          } catch (e) {
            console.error('Failed to parse JSON:', json, e)
          }
        }
      }
    } finally {
      reader.releaseLock()
    }
  } catch (error) {
    console.error('Stream processing error:', error)
    throw error
  }
} 